package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.ITravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private ITravelCommentRepository travelCommentRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public TravelComment saveOrUpdate(TravelComment comment) {
        if (!StringUtils.hasLength(comment.getId())) {
            comment.setCreateTime(new Date());
        }

        if (comment.getType() == TravelComment.TRAVLE_COMMENT_TYPE) {
            Optional<TravelComment> op = travelCommentRepository.findById(comment.getRefComment().getId());
            TravelComment travelComment = op.get();
            comment.setRefComment(travelComment);
        }

        travelCommentRepository.save(comment);
        return comment;
    }

    @Override
    public List<TravelComment> query(TravelCommentQuery qo) {
        Query query = new Query();
        query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        query.with(Sort.by(Sort.Direction.ASC, "createTime"));
        List<TravelComment> list = mongoTemplate.find(query, TravelComment.class);

        return list;
    }

    @Override
    public List<TravelComment> findFirstTen() {
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.DESC, "createTime")).skip(0).limit(10);
        List<TravelComment> list = mongoTemplate.find(query, TravelComment.class);
        return list;
    }
}
